<!DOCTYPE html>
<html>
<head>

<link href="./css/smoothness/ui.min.css" type="text/css" rel="stylesheet" media="all" />
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="./js/ui.min.js" type="text/javascript"></script>
<script src="./js/highcharts.js" type="text/javascript"></script>
<script src="./js/gw2money.js" type="text/javascript"></script>
<script type="text/javascript">

var	ALERT_DELAY = 5 * 60 * 1000, //limit automatic playing of alerts to once every 5 minutes
	GEM_UPDATE_DELAY = 60 * 1000; //update gem price once a minute. note the graph updates once every 5 seconds
	
Highcharts.setOptions({global: { useUTC: false }});

var series,
	chart,
	timer_key,
	coinLimit,
	gemPrice,
	timer_audio,
	lastAlert,
	updateCoinOnNext;

function init()
{
	update();
	
	$("#volume-slider").slider({
		orientation: "horizontal",
		range: "min",
		min: 0,
		max: 100,
		value: 100,
		step: 5,
		slide: function(event, ui) {
			document.getElementById("audio").volume = (ui.value / 100);
		}
	});
	$("#play").button({
		text: false,
		icons: {
			primary: "ui-icon-play"
		}
	})
	.click(function() {
		if ($(this).text() === "play") {
			playAudio();
		} else {
			pauseAudio();
		}
	});
	
	var a = document.getElementById("audio");
	a.addEventListener("ended", pauseAudio);
	a.load();
}

function playAudio()
{
	var options,
		a = document.getElementById("audio"),
		b = $("#play"),
		loop = document.getElementById("audio-loop").checked == true;
		
	a.currentTime = 0;
	a.loop = loop;
	a.play();
	
	options = {
		label: "pause",
		icons: {
			primary: "ui-icon-pause"
		}
	};
	b.button("option", options);
	
	var f = function()
	{
		b.stop().css("opacity", "1.0").animate({ opacity: "0.5"}, 1000, function()
		{
			b.stop().css("opacity", "0.5").animate({ opacity: "1.0"}, 1000, f);
		});
	}
	f();
}

function pauseAudio()
{
	var options,
		a = document.getElementById("audio"),
		b = $("#play");
		
	a.pause();
	options = {
		label: "play",
		icons: {
			primary: "ui-icon-play"
		}
	};
	b.button("option", options);
	b.stop().css("opacity", "1.0");
	
	if (timer_audio)
	{
		clearTimeout(timer_audio);
		timer_audio = null;
	}
}

function initChart(initialValue)
{
	var data = [[],[]], time = (new Date()).getTime(), i;
	
	//1 tick every 5 seconds for 30 min
	for (i = -30 * 60 / 5; i <= 0; i++) {
		data[0].push([
			time + i * 5 * 1000,
			i > -12 ? initialValue : null
		]);
		data[1].push([
			time + i * 5 * 1000,
			null
		]);
	}
				
	var container = document.getElementById("chart"),
	options = {
		chart : {
			renderTo: container,
			events : {
				load : function() {
					series = this.series;
				}
			}
		},
		
		tooltip: {
            formatter: function() {
				var series = this.series,
					point = this.point,
					age = Math.floor((new Date().getTime() - this.x) / 60000);
					
				age = age < 1 ? "Less than a minute ago" : age == 1 ? "A minute ago" : age + " minutes ago";
				
				return "<span style=\"font-size: 10px\">" + age + "</span><br/>" +
					'<b>' + formatGW2Money(point.y) + '</b> <br />';
            },
            useHTML: true,
			borderColor: '#4572a7'
        },
		
		title: {
			text: null,
		},
		
		legend: {
			enabled: false,
		},
		
		series : [{
			type: 'spline',
			data: data[0],
			color: '#4572a7'
		},{
			type: 'areaspline',
			data: data[1],
			color: '#44A747'
		}],
		
		scrollbar: {
			enabled: false
		},
		
		navigator: {
			enabled: false
		},
		
		plotOptions: {
				series: {
					animation: false
				},

                areaspline: {
                    fillColor: {
                        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
                        stops: [
                            [0, Highcharts.Color('#44A747').setOpacity(0.8).get('rgba')],
                            [1, Highcharts.Color('#44A747').setOpacity(0.4).get('rgba')]
                        ]

                    },
                    lineWidth: 2,
                    marker: {
                        enabled: false
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 2,
                        }
                    },
                    threshold: null,
                },
				
				spline: {
					lineWidth: 2,
                    marker: {
                        enabled: false
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 2,
                        }
                    },
				}
            },
		
		xAxis: {
			title: {
				text: null
            },
			type: 'datetime',
			tickInterval: 5 * 60 * 1000,
			dateTimeLabelFormats: {
				second: '%H:%M'
			},
		},
		
		yAxis: {
			title: {
				text: null
            },
			minRange: 100,
			minTickInterval: 50,
			tickPixelInterval: Math.floor(container.clientHeight / 5),
			labels: {
				formatter: function() {
				   return formatGW2Money(this.value);
				},
				useHTML: true
			}
		},
	};
	chart = new Highcharts.Chart(options);
}

function update()
{	
	/*
	//data demo
	var first = !gemPrice;
	gemPrice = 35000 + Math.round(Math.random() * 100);
	first && render();
	setTimeout(update, 10000);
	return;
	*/
	
	var r = $.getJSON("http://www.gw2spidy.com/api/v0.9/json/gem-price?callback=?")
	r.done(
		function(data) {
			var first = !gemPrice,
				p = data.result.gold_to_gem
				changed = p != gemPrice;
			gemPrice = p;
			first && render();
			changed && updateDifference();
		}
	).always(
		function() {
			setTimeout(update, document.getElementById("update-freq").value || GEM_UPDATE_DELAY);
		});
}

function render() {
	var x = new Date().getTime(),
		y = gemPrice,
		limit;
	
	if (!chart)
	{
		initChart(y);
		if (updateCoinOnNext)
			updateCoin();
	}
	else
	{
		limit = coinLimit && y <= coinLimit.value;
		series[0].addPoint([x, y], true, true);
		series[1].addPoint([x, limit ? y : null], true, true);
		
		if (limit && !timer_audio && document.getElementById("audio-enabled").checked == true && (!lastAlert || new Date().getTime() - lastAlert > ALERT_DELAY))
		{
			lastAlert = new Date().getTime();
			playAudio();
			
			if (document.getElementById("audio-loop").checked == true)
			{
				var d = document.getElementById("audio").duration,
					t = Math.max(!isNaN(d) ? d * 1000 : 0, 30000);
				timer_audio = setTimeout(pauseAudio, t); //auto stop after 30s
			}
		}
	}
	
	setTimeout(render, 5000);
}

function updateDifference()
{
	var d = document.getElementById("diff"),
		dg = document.getElementById("diff-g"),
		ds = document.getElementById("diff-s"),
		dc = document.getElementById("diff-c"),
		l = coinLimit && coinLimit.value || 0,
		diff = Math.abs(l - gemPrice),
		g = Math.floor(diff / 10000)
		s = Math.floor(diff / 100) % 100
		c = diff % 100;
	
	g > 0 && (dg.innerHTML = g);
	s > 0 && (ds.innerHTML = s);
	(c > 0 || g == 0 && s == 0) && (dc.innerHTML = c);
	
	d.style.display = l > gemPrice ? "inline" : "none";
	dg.style.display = g > 0 ? "inline" : "none";
	ds.style.display = s > 0 ? "inline" : "none";
	dc.style.display = c > 0 || g == 0 && s == 0 ? "inline" : "none";
	
	ds.style.paddingLeft = g > 0 ? "5px" : "0px";
	dc.style.paddingLeft = g > 0 || s > 0 ? "5px" : "0px";
}

function coin_keypress(e)
{
	if (e.keyCode < 48 || e.keyCode > 57)
	{
		e.preventDefault();
		return;
	}
}

function coin_changed(e)
{
	var i = parseInt(e.value);
	if (isNaN(i))
		e.value = "0";
		
	timer_key && clearTimeout(timer_key);
	timer_key = setTimeout(updateCoin, 1000);
}

function coin_keyup(e)
{
	timer_key && clearTimeout(timer_key);
	timer_key = setTimeout(updateCoin, 1000);
}

function updateCoin()
{
	if (!chart)
	{
		updateCoinOnNext = true;
		return;
	}
	
	var g = parseInt(document.getElementById("gold").value),
		s = parseInt(document.getElementById("silver").value),
		c = parseInt(document.getElementById("copper").value),
		total = g * 10000 + s * 100 + c;
		
	if (coinLimit)
	{
		if (coinLimit.value == total)
			return;
		coinLimit.line.destroy();
	}
	
	coinLimit = total > 0 && {
		value: total,
		line: function()
			{
				var yAxis = chart.yAxis[0],
				i = yAxis.plotLinesAndBands.length;
				yAxis.addPlotLine({
					value: total,
					width: 3,
					color: '#ff0000'
				});
				
				return yAxis.plotLinesAndBands[i];
			}()
	};
	
	if (coinLimit) //update the existing graph points to show the limit
	{
		var p0 = series[0].points,
			p1 = series[1].points,
			l = p0.length,
			updated = false;
		
		for (var i = 0; i < l; i++)
		{
			var p = p0[i];
			if (p.y && p.y <= total && p1[i].y != p.y)
			{
				p1[i].update([p.x, p.y], false);
				updated = true;
			}
			else
			{
				p = p1[i];
				if (p.y && p.y > total)
				{
					p.update([p.x, null], false);
					updated = true;
				}
			}
		}
		
		if (updated)
		{
			chart.redraw();
		}
	}
	
	updateDifference();
}

function audioEnabled()
{
	lastAlert = null; //remove the limit when enabling/disabling audio
}

</script>

<style type="text/css">

body {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
}
.gw2money-copper,
.gw2money-silver,
.gw2money-gold {
    display: inline-block;
    width: 15px;
    height: 15px;
    vertical-align: middle;
    background: transparent no-repeat;
    text-indent: -1999px;
    overflow: hidden;
}
.gw2money-copper {
    background-image: url('./images/copper.png');
}
.gw2money-silver { 
    background-image: url('./images/silver.png'); 
}
.gw2money-gold {
    background-image: url('./images/gold.png');  
}
#gold, #silver, #copper {
	width: 30px;
	text-align: right;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px; 
}
.container {
	width: 100%;
	min-width: 500px;
}
#diff-s,#diff-c
{
	padding-left: 5px;
}
#diff-g:after
{
	content: '';
    background: url('./images/gold.png') no-repeat 3px 0;
	padding-right: 18px;
}
#diff-s:after
{
	content: '';
    background: url('./images/silver.png') no-repeat 3px 0;
	padding-right: 18px;
}
#diff-c:after
{
	content: '';
    background: url('./images/copper.png') no-repeat 3px 0;
	padding-right: 18px;
}

</style>

</head>
<body onLoad="init()">

<div class="container" id="chart" style="height: 300px"></div>

<div class="container" style="position: relative;">

    <div style="position: absolute; top: 0px; left: 0px;">
        <div id="volume-slider" style="width: 100px; display: inline-block; position: relative; top: 3px;"></div>
        <button id="play" style="width: 30px; height: 20px; display: inline-block; margin-left: 10px;">play</button>
        <div>
    		<input type="checkbox" checked="checked" id="audio-enabled" style="position: relative; top: 2px;" onChange="audioEnabled()" /> Enable
        	<input type="checkbox" checked="checked" id="audio-loop" style="position: relative; top: 2px; margin-left: 5px;" /> Loop
        </div>
        <div style="margin-top: 15px;">
        	Update every <select id="update-freq"><option value="10000">10s</option><option value="30000">30s</option><option value="60000" selected="selected">1m</option><option value="30000">5m</option></select>
        </div>
    </div>
    <p style="text-align:right;">I want to buy 100 gems at <input type="text" value="0" id="gold" onKeyPress="coin_keypress(event)" onKeyUp="coin_keyup(this)" onChange="coin_changed(this)" /> <span class="gw2money-gold"></span> <input type="text" value="0" id="silver" maxlength="2" onKeyPress="coin_keypress(event)" onKeyUp="coin_keyup(this)" onChange="coin_changed(this)" /> <span class="gw2money-silver"></span> <input type="text" value="0" id="copper" maxlength="2" onKeyPress="coin_keypress(event)" onKeyUp="coin_keyup(this)" onChange="coin_changed(this)" /> <span class="gw2money-copper"></span> or less.</p>
    <p style="text-align: right; font-size: 12px; opacity: 0.5;">Current difference is <span id="diff">-</span><span id="diff-g">0</span><span id="diff-s">0</span><span id="diff-c">0</span></p>
</div>

<audio id="audio" style="display: none;">
	<source src="./sounds/alert.mp3" type="audio/mpeg">
</audio>

</body>
</html>